package game.engine.base

import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint


/**
 *  Label 取消铆点这个概念,也没有宽高这个概念. 只有左 中 右  对齐 坐标
 *  1. 是否需要支持换行?
 *  2. 是否需要支持自动换行?
 *
 */
class Label(var text: String,align:Paint.Align = Paint.Align.LEFT) : Node() {

    val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    var textColor = Color.RED
        set(value) {
            field = value
            paint.color = value
        }

    var textSize = 30f
        set(value) {
            field = value
            paint.textSize = value
        }

    var align = align
        set(value) {
            field = value
            paint.textAlign = value
        }

    // for debug
    val debugMatrix: Matrix by lazy {
        Matrix()
    }

    init {
        paint.color = textColor
        paint.textSize = textSize
        paint.textAlign = align
    }

    override fun updateFinalMatrixInRender(parentMatrix: Matrix) {

        //
        val fm = paint.fontMetrics
        val texHeight = fm.bottom - fm.top
        val baseLineYOffset = texHeight / 2f - fm.bottom;

        finalMatrix.set(parentMatrix)
        finalMatrix.preTranslate(x, y + baseLineYOffset)
        finalMatrix.preRotate(degress)
        finalMatrix.preScale(sx, sy)

        // for debug
        if (CoreDebug.LabelDebug) {
            debugMatrix.set(parentMatrix)
            debugMatrix.preTranslate(x, y)
            debugMatrix.preRotate(degress)
            debugMatrix.preScale(sx, sy)
        }

    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // for debug
        if (CoreDebug.LabelDebug) {
            canvas.setMatrix(debugMatrix)
            val texWidth = paint.measureText(text)
            val fontMetrics = paint.fontMetrics
            val texHeight = fontMetrics.bottom - fontMetrics.top
            paint.color = Color.WHITE
            when(align){
                Paint.Align.LEFT -> canvas.drawRect(0f, -texHeight / 2f, texWidth, texHeight / 2f, paint)
                Paint.Align.CENTER -> canvas.drawRect(-texWidth/2f, -texHeight / 2f, texWidth/2f, texHeight / 2f, paint)
                Paint.Align.RIGHT -> canvas.drawRect(-texWidth, -texHeight / 2f, 0f, texHeight / 2f, paint)
            }
            paint.color = textColor
        }

        //
        canvas.setMatrix(finalMatrix)
        canvas.drawText(text, 0f, 0f, paint)
    }


}